import React from 'react';
import * as Select from '@radix-ui/react-select';
import styles from './index.module.scss';

import Image from 'next/image';
import { ChevronDown, Check } from 'lucide-react';
import classNames from 'classnames';

import { withConsumer } from '../../../context';
import { connect } from 'react-redux';
import { update } from '@/utils/immutableUtil';
import { getConfigs, getEnabledModelList } from '@/api/ai';

import router from 'next/router';
import _ from 'lodash';

@withConsumer
@connect(({ chat }) => ({
  templatesList: chat.templatesList,
  selectedModel: chat.selectedModel,
}))
class Comp extends React.Component {
  componentDidMount() {
    this.getTemplatesData();
  }

  getImg = (key) => {
    var base = '';
    if (router.basePath) {
      base = router.basePath;
    }
    var map = {
      azure: `${base}/img/models/azure.png`,
      openai: `${base}/img/models/openai.png`,
      tongyi: `${base}/img/models/tongyi.png`,
      deepseek: `${base}/img/models/deepseek.png`,
      anthropic: `${base}/img/models/anthropic.png`,
      default: `${base}/img/models/default.png`,
    };
    return map[key] ||map['default'];
  };

  getTemplatesData = async () => {
    const {
      value: { changeState },
    } = this.props;
    var reqData = {};
    var rs = await getEnabledModelList(reqData);

    if (rs.data?.code == 200) {
      var data = rs.data.data.map((item, i) => {
        return {
          ...item,
          icon: this.getImg(item.firm),
          id: item.id,
          name: item.model,
          model: item.model,
        };
      });

      var selectedModel = window.localStorage.getItem('selectedModel') || '';
      var id = selectedModel;

      // 有缓存
      if (selectedModel) {
        var item = _.find(data, { id: selectedModel });
        // 假如缓存的id没有数据，取第一个
        if (!item && data[0]) {
          id = data[0].id;
        }
      }

      // 没缓存 没数据
      if (!selectedModel && data[0]) {
        id = data[0].id;
      }
      changeState({ selectedModel: id, templatesList: data });
      window.localStorage.setItem('selectedModel', id);
    }
  };

  getSelectedModel = (value) => {
    const { templatesList } = this.props;
    return templatesList.find((model) => model.id === value);
  };

  chunk = (arr, size) => {
    return Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
      arr.slice(i * size, i * size + size),
    );
  };

  handleValueChange = (value) => {
    const {
      value: { changeState, controller, inputFocus },
    } = this.props;
    changeState({ selectedModel: value });
    window.localStorage.setItem('selectedModel', value);

    setTimeout(() => {
      inputFocus();
    }, 300);
  };

  shouldComponentUpdate = (np, ns) => update.call(this, np, ns);
  render() {
    const { templatesList, selectedModel } = this.props;
    const currentModel = this.getSelectedModel(selectedModel);

    return (
      <div className={styles.container}>
        {currentModel && (
          <>
            <Select.Root
              value={selectedModel}
              onValueChange={this.handleValueChange}
            >
              <Select.Trigger
                disabled={false}
                className={classNames(styles.trigger, {
                  [styles.open]: true,
                })}
                aria-label="Select model"
              >
                <div className={styles.triggerContent}>
                  <div className={styles.modelIcon}>
                    <img src={currentModel.icon} alt={currentModel.name} />
                  </div>
                  <div className={styles.title}>{currentModel.model}</div>
                </div>
                <Select.Icon
                  className={classNames(styles.selectIcon, {
                    [styles.open]: true,
                  })}
                >
                  <ChevronDown size={14} />
                </Select.Icon>
              </Select.Trigger>

              <Select.Portal>
                <Select.Content
                  className={styles.content}
                  position="popper"
                  sideOffset={8}
                  align="center"
                >
                  <Select.Viewport>
                    <div className={styles.modelRow}>
                      {templatesList.map((model) => (
                        <Select.Item
                          key={model.id}
                          value={model.id}
                          className={classNames(styles.item, {
                            [styles.selected]: selectedModel === model.id,
                          })}
                        >
                          <div className={styles.modelIcon}>
                            <img src={model.icon} alt={model.name} />
                          </div>
                          <div className={styles.modelName}>{model.name}</div>
                          <Check size={16} className={styles.itemCheckIcon} />
                        </Select.Item>
                      ))}
                    </div>
                  </Select.Viewport>
                </Select.Content>
              </Select.Portal>
            </Select.Root>
          </>
        )}
      </div>
    );
  }
}

export default Comp;
